import {
  ArgumentMetadata,
  HttpException,
  HttpStatus,
  Injectable,
  PipeTransform,
} from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { Type } from '@nestjs/common';
import { validate } from 'class-validator';

@Injectable()
export class PipeVerifyPipe implements PipeTransform {
  // value:前端传过来的数据 
  // metaData:元数据 通过 metatype 实例化这个类
  async transform(value: any, metadata: ArgumentMetadata) {
    console.log('value', value, 'metadata', metadata.metatype);
    // Type<any> 类型构造函数
    const DTO = plainToInstance(metadata.metatype as Type<any>, value);
    const errors = await validate(DTO);
    if (errors.length) {
      // 如果有异常拦截器，会被异常拦截器捕获处理
      throw new HttpException(errors, HttpStatus.BAD_REQUEST);
    }
    return value;
  }
}
